using System;
using UnityEngine;
namespace NL.Advanced
{
    public class CommandExcuter_AnyCall : MonoBehaviour, ICommandExcute
    {
        public void Excute(NLIni ini)
        {

            // opt=StaticFuction
            // opt= GameObjectSendMessage
            var type = ini["type"].AsString;

            switch (type.ToLower())
            {
                case "staticfunction":
                    _StaticCall(ini); break;
                case "gameobjectsendmessage":
                    _GameObjectSendMessage(ini); break;
            }


        }

        public void Excute(string message, params object[] args)
        {

        }


        void _StaticCall(NLIni ini)
        {
            var classname = ini["class"].AsString;
            var function = ini["opt"].AsString;

            var t = _GetTypeByName(classname);

            if (t == null) return;

            var method = t.GetMethod(function);

            if (method == null) return;


            try
            {
                method.Invoke(null, null);
                LOG.Add($"[CommandExcuter_AnyCall._StaticCall]:{classname}.{function}()...");

            }
            catch (Exception e)
            {
                LOG.Add($"[CommandExcuter_AnyCall._StaticCall]:{classname}.{function}()...Error={e.Message}");
            }
        }

        void _GameObjectSendMessage(NLIni ini)
        {
            var objectname = ini["who"].AsString;
            var function = ini["opt"].AsString;

            var ob = GameObject.Find(objectname);

            if (ob == null) return;

            try
            {
                ob.SendMessage(function, SendMessageOptions.DontRequireReceiver);
                LOG.Add($"[CommandExcuter_AnyCall._GameObjectSendMessage]:{objectname}.{function}()...");
            }
            catch (Exception e)
            {
                LOG.Add($"[CommandExcuter_AnyCall._StaticCall]:{objectname}.{function}()...Error={e.Message}");
            }
        }


        static Type _GetTypeByName(string name)
        {
            foreach (var domain in System.AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (var t in domain.GetTypes())
                {
                    if (t.Name == name)
                        return t;
                }
            }
            return null;
        }
    }
}

